import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { Observable } from 'rxjs';
import { ROLES_KEY } from '../decorator/require-role.decorator';
import { RoleEnum } from '../enum';

@Injectable()
export class RoleGuard implements CanActivate {
  constructor(private readonly reflector: Reflector) {}
  canActivate(context: ExecutionContext): boolean | Promise<boolean> | Observable<boolean> {
    const req = context.switchToHttp().getRequest();
    const roles: RoleEnum[] = this.reflector.getAllAndOverride(ROLES_KEY, [context.getClass(), context.getHandler()]);
    if (roles) {
      const user = req.user;
      const userRoleIds = user.roles.map((item) => item.roleId);
      // 校验身份 只需满足接口所需身份中的其中一个即可
      const hasRole: boolean = roles.some((role) => userRoleIds.includes(role));
      return hasRole;
    }
    // 如果接口没有设置身份 则不需要校验
    return true;
  }
}
